package com.vx.xmlModelToData.demo;

import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class BeanXMLTest <T> {
	public  void beanToXML(Class cl,List<T> entityPropertys,String encode,String filePath) throws  Exception{
		OutputFormat format=OutputFormat.createPrettyPrint();
		format.setEncoding(encode);
		File file=new File(filePath);
		
		Document doc=DocumentHelper.createDocument();
		String rootName=cl.getSimpleName();
		Element root=doc.addElement(rootName+"s");
		Field[] fields=cl.getDeclaredFields();
		for (T t : entityPropertys) {
			Element secondRoot=root.addElement(rootName);
			for(int i=0;i<fields.length;i++){
				Method getMethod=t.getClass().getMethod("get"+getMethodName(fields[i].getName()));
				secondRoot.addElement(fields[i].getName()).setText(getMethod.invoke(t).toString());
			}
		}
		
		XMLWriter xmlWriter=new XMLWriter(new FileWriter(file), format);
		xmlWriter.write(doc);
		xmlWriter.close();
		System.out.println(doc.asXML());
		
	}
	public static void main(String[] args) throws Exception {
		BeanXMLTest<User> demo=new BeanXMLTest<User>();
		User u1=new User("姓名A",20,"男");
		User u2=new User("姓名B",19,"女");
		List<User> list=new ArrayList<User>();
		list.add(u1);
		list.add(u2);
		demo.beanToXML(User.class, list, "UTF-8", "students.xml");
	}
	
	/**
	   * 获取方法名 
	   * <p>
	   * 把一个字符串的第一个字母大写、效率是最高的
	   * </p>
	   * @param fildeName
	   * @return
	   * @throws Exception
	   */
	  private static String getMethodName(String fildeName) throws Exception{  
	      byte[] items = fildeName.getBytes();  
	      items[0] = (byte) ((char) items[0] - 'a' + 'A');  
	      return new String(items);  
	  } 
}

class User{
	private String name;
	private int age;
	private String xb;
	
	
	public User(String name, int age, String xb) {
		super();
		this.name = name;
		this.age = age;
		this.xb = xb;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getXb() {
		return xb;
	}
	public void setXb(String xb) {
		this.xb = xb;
	}
	
	
}